<template>
  <uv-navbar :fixed="false" :title="title" left-arrow @leftClick="$onClickLeft"/>
  <view class="container position-relative">
    <view style="margin-bottom: 130rpx;">
      <!-- 购物车列表 begin -->
      <view class="section-2">
        <view class="cart d-flex flex-column">
          <list-cell last v-for="(item, index) in cart" :key="index">
            <view class="w-100 d-flex flex-column">
              <view class="d-flex align-items-center mb-10">
                <view class="d-flex flex-fill justify-content-between align-items-center text-color-base font-size-lg">
                  <image style="width: 80rpx;height: 80rpx;" mode="aspectFill" :src="item.image"></image>
                </view>
                <view class="name-and-props overflow-hidden">
                  <view class="text-color-base font-size-lg">{{ item.name }}</view>
                </view>
                <view class="d-flex flex-fill justify-content-between align-items-center text-color-base font-size-lg">
                  <view>x{{ item.number }}</view>
                </view>
              </view>
            </view>
          </list-cell>
        </view>
      </view>
      <!-- 购物车列表 end -->
      <!-- 支付方式 begin -->
      <view class="payment">
        <list-cell last :hover="false">
          <text>支付方式</text>
        </list-cell>
        <list-cell last>
          <view class="d-flex align-items-center justify-content-between w-100 disabled">
            <view class="iconfont iconbalance line-height-100 payment-icon"></view>
            <view class="flex-fill">余额支付（余额：{{'\u221E'}}）</view>
            <view class="iconfont line-height-100 checkbox checked iconradio-button-on" v-if="payType === 'yue'"></view>
          </view>
        </list-cell>
      </view>
      <!-- 支付方式 end -->
      <!-- 备注 begin -->
      <list-cell last @click="goToRemark">
        <view class="d-flex flex-fill align-items-center justify-content-between overflow-hidden" style="margin-bottom: 110rpx;">
          <view class="flex-shrink-0 mr-20">备注</view>
          <view class="text-color-primary flex-fill text-truncate text-right">{{ form.remark || '点击填写备注' }}</view>
        </view>
      </list-cell>
      <!-- 备注 end -->
    </view>
    <!-- 付款栏 begin -->
    <view style="z-index: 1;" class="w-100 pay-box position-fixed fixed-bottom d-flex align-items-center justify-content-between bg-white">
      <view class="font-size-sm" style="margin-left: 20rpx;"></view>
      <view class="font-size-lg flex-fill"></view>
      <view class="bg-primary h-100 d-flex align-items-center justify-content-center text-color-white font-size-base" style="padding: 0 60rpx;" @tap="debounce(submit, 500)">付款</view>
    </view>
    <!-- 付款栏 end -->
    <modal :show="ensureAddressModalVisible" custom :mask-closable="false" :radius="'0rpx'" width="90%">
      <view class="modal-content">
        <view class="d-flex justify-content-end">
          <image src="/static/images/pay/close.png" style="width: 40rpx; height: 40rpx;" @tap="ensureAddressModalVisible = false"></image>
        </view>
        <view class="d-flex justify-content-center align-items-center" style="margin-bottom: 40px;">
          <view class="font-size-extra-lg text-color-base">请再次确认下单地址</view>
        </view>
        <view class="d-flex font-size-base text-color-base font-weight-bold align-items-center justify-content-between mb-20">
          <view>{{ address.realName }}</view>
          <view>{{ address.phone }}</view>
        </view>
        <view class="d-flex font-size-sm text-color-assist align-items-center justify-content-between mb-40">
          <view style="max-width: 60%;">{{ address.address + address.detail }}</view>
          <button type="primary" size="mini" plain class="change-address-btn" style="white-space: nowrap;" @click="chooseAddress">修改地址</button>
        </view>
        <button type="primary" class="pay_btn" @tap="debounce(pay, 500)">确认并付款</button>
      </view>
    </modal>
    <uv-toast ref="uToast"></uv-toast>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useMainStore } from '@/store/store'
import { storeToRefs } from 'pinia'
import { onLoad, onShow } from '@dcloudio/uni-app'
import debounce from '@/uni_modules/uv-ui-tools/libs/function/debounce'
import { orderSubmit, payUnify } from '@/api/order'
import ListCell from "@/components/list-cell/list-cell.vue";
import UvNavbar from "@/uni_modules/uv-navbar/components/uv-navbar/uv-navbar.vue";
import UvToast from "@/uni_modules/uv-toast/components/uv-toast/uv-toast.vue";
import Modal from "@/components/modal/modal.vue";

const main = useMainStore()
const { address, store, member } = storeToRefs(main)

const title = ref('支付')
const cart = ref([])
const form = ref({ remark: '' })
const ensureAddressModalVisible = ref(false)
const payType = ref('yue') // 付款方式

// 计算购物车总价
const total = computed(() => cart.value.reduce((acc, cur) => acc + cur.number * cur.price, 0))

// 计算实际支付金额，保留两位小数
const amount = computed(() => total.value.toFixed(2))

// 页面显示时初始化数据
onShow(() => {
  cart.value = uni.getStorageSync('cart')
})

// 跳转到备注页面
const goToRemark = () => {
  uni.navigateTo({ url: `/pages/components/pages/remark/remark?remark=${form.value.remark}` })
}

// 跳转到地址选择页面
const chooseAddress = () => {
  uni.navigateTo({ url: '/pages/components/pages/address/address?is_choose=true&scene=pay' })
}

// 提交订单
const submit = () => {
  pay()
}

// 支付逻辑
const pay = async () => {
  // #ifdef MP-WEIXIN
  await new Promise(revolve => {
    const subscribeMss = ['KBtfY9G1IWCzC6q-ZKo-Q-MmdP7aaF79nx0XFcBf3h4']
    wx.showModal({
      title: '温馨提示',
      content: '为更好的促进您与商家的交流，小程序需要在您成交时向您发送消息',
      confirmText: "同意",
      cancelText: "拒绝",
      success: res => {
        if (res.confirm) {
          uni.requestSubscribeMessage({
            tmplIds: subscribeMss,
            complete: res => {
              console.log(res)
              revolve(true)
            }
          })
        } else {
          revolve(true)
        }
      }
    })
  })
  // #endif

  uni.showLoading({ title: '加载中' })

  const data = {
    shop_id: store.value.id,
    mobile: member.value.mobile,
    pay_type: payType.value,
    remark: form.value.remark,
    product_id: [],
    spec: [],
    number: [],
  }

  cart.value.forEach(item => {
    data.product_id.push(item.id)
    data.number.push(item.number)
  })

  const order = await orderSubmit(data)
  if (!order) {
    uni.hideLoading()
    return
  }

  // 执行余额支付
  balancePay(order)
  uni.hideLoading()
}

// 余额支付逻辑
const balancePay = async (order) => {
  let from = 'routine'
  // #ifdef H5
  from = 'h5'
  // #endif

  const pay = await payUnify({ order_sn: order.orderId, from, pay_type: 'yue' })
  if (!pay) return

  member.value.money -= amount.value
  main.SET_MEMBER(member.value)
  uni.setStorageSync('cart', JSON.parse(JSON.stringify([])))
  uni.switchTab({ url: '/pages/order/order' })
}
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
}

.arrow {
  width: 50rpx;
  height: 50rpx;
  position: relative;
  margin-right: -10rpx;
}

.location {
  .store-name {
    font-size: $font-size-lg;
  }

  .iconfont {
    font-size: 50rpx;
    line-height: 100%;
    color: $color-primary;
  }
}

.section-2 {
  .name-and-props {
    width: 65%;
  }
}

.payment {
  margin-bottom: 30rpx;

  .disabled {
    color: $text-color-grey;
  }

  .payment-icon {
    font-size: 44rpx;
    margin-right: 10rpx;
  }

  .checkbox {
    font-size: 36rpx;
    margin-left: 10rpx;
  }

  .checked {
    color: $color-primary;
  }
}

.pay-box {
  box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);
  height: 100rpx;
}

.modal-content {
  .change-address-btn {
    line-height: 2;
    padding: 0 1em;
  }

  .pay_btn {
    width: 100%;
    border-radius: 50rem !important;
    line-height: 3;
  }
}
</style>
